package org.aokey.springdemo2.day62;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/Session")
public class GetSessionController {
    @RequestMapping("/A1")
    public String A1(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies=request.getCookies();
        StringBuilder stringBuilder=new StringBuilder();
        if(cookies!=null){
            for(Cookie ck:cookies){
                stringBuilder.append(ck.getName()+"="+ck.getValue());
            }
        }
        return stringBuilder.toString();
    }
    @RequestMapping("/A2")
    public String A2(@CookieValue("name") String name){
        return  "name为："+name;
    }
    @RequestMapping("/A3")
    public String A3(HttpServletRequest request){
        HttpSession session=request.getSession();
        if (session!=null){
            session.setAttribute("userName","Aokey");
            session.setAttribute("age",18);
        }
        return "Session设置成功";
    }
    @RequestMapping("/A4")
    public String A4(HttpServletRequest request){
        HttpSession session=request.getSession(false);
        if(session==null){
            return "用户未登录";
        }else {
            String userName=(String) session.getAttribute("userName");
            Integer age=(Integer) session.getAttribute("age");
            return "姓名："+ userName+" 年龄："+age;
        }
    }
    @RequestMapping("/A5")
    public String A5(@SessionAttribute("userName" ) String userName,@SessionAttribute("age") Integer age){
        return "姓名："+ userName +" 年龄："+age;
    }
    @RequestMapping("/A6")
    public String A6(HttpSession session){
        String userName=(String) session.getAttribute("userName");
        Integer age=(Integer) session.getAttribute("age");
        return "姓名："+ userName +" 年龄："+age;
    }
    @RequestMapping("/A7")
    public String A7(HttpServletRequest request){
        String string=request.getHeader("Cookie");
        return "获取到Cookie为："+string;
    }
    @RequestMapping("/A8")
    public String A8(@RequestHeader("Cookie")  String string){
        return "获取到Cookie为："+string;
    }
}
